package org.mixed.core.interceptor;

import org.mixed.core.domain.SysUser;
import org.mixed.core.exception.LoginException;
import org.mixed.core.utils.MD5Utils;

import java.util.Objects;

public class DefaultAuthorizationInterceptor implements AuthorizationInterceptor {

	private final boolean requireLogin;
	private String validToken;
	private SysUser configSysUser;

	public DefaultAuthorizationInterceptor(String username, String password) {
		requireLogin = username != null && password != null;
		if (requireLogin) {
			validToken = MD5Utils.encrypt(String.format("%s||%s", username, password));
			configSysUser = new SysUser(username, username, this.validToken);
		}
	}

	@Override
	public boolean requireLogin() {
		return this.requireLogin;
	}

	@Override
	public SysUser getUserByToken(String token) throws LoginException {
		if (requireLogin && Objects.equals(validToken, token)) {
			return configSysUser;
		}
		throw new LoginException("token无效");
	}

	@Override
	public SysUser login(String username, String password) throws LoginException {
		if (requireLogin && Objects.equals(MD5Utils.encrypt(String.format("%s||%s", username, password)), this.validToken)) {
			return configSysUser;
		}
		throw new LoginException("用户名或密码不正确");
	}
}
